import threading
import time


class Prosumer:
    def __init__(self):
        self.list = list()
        self.thread = None


class ProducerTask:
    def __init__(self, ip, method, value):
        self.ip = ip
        self.method = method
        self.value = value


class Producer(Prosumer):
    def push(self, ip: str, method: str, value: object):
        self.list.append(ProducerTask(ip, method, value))


class ConsumerTask:
    def __init__(self, ip, code, message, data):
        self.ip = ip
        self.code = code
        self.message = message
        self.data = data


class Consumer(Prosumer):
    def push(self, ip: str, code: str, message: str, data: object):
        _key = time.time()
        self.list.append(ConsumerTask(ip, code, message, data))

    def pop(self, ip):
        for i in self.list:
            if i.ip == ip:
                self.list.remove(i)
                return i.__dict__
        return False


PRODUCER = Producer()
CONSUMER = Consumer()
PROSUMER = Prosumer()


def producer_to_consumer():
    global PRODUCER
    global CONSUMER
    while 1:
        if len(PRODUCER.list) == 0:
            time.sleep(1)
            continue
        task = PRODUCER.list.pop()
        res = task.method(task.value)
        if res is None:
            continue
        CONSUMER.push(task.ip, res["code"], res["msg"], res["data"])


PROSUMER.thread = threading.Thread(target=producer_to_consumer, args=())
PROSUMER.thread.setDaemon(True)
PROSUMER.thread.start()